﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GatewayInspect.Common;
using System.Data.OracleClient;

namespace GatewayInspect.Modules
{
    public partial class FKJLModule : BaseModule
    {
        public FKJLModule()
        {
            InitializeComponent();
        }

        protected override void OnInitialize()
        {
            base.OnInitialize();

            foreach (ToolStripItem item in this.tsMain.Items)
            {
                if (item != tsBtnClose)
                {
                    item.Visible = false;
                }
            }
        }

        private void ReLoad()
        {
            string strSql = "select CARDID,CHEHAO,SENDCARDTIME,SENDCARDMAN,HD_WEIGHT,CARDSTATE,decode(CARDSTATE, '0', '可用', '作废') as CARDSTATE_XS," +
                "decode(QG_BS, '3', '黄岛', '董家口') as ADDR,decode(a.ORGCODE,'1','01',a.ORGCODE) as ORGCODE,b.ORGNAME " +
                "from RFID_READ a left join T_SYS_ORG b on decode(a.ORGCODE,'1','01',a.ORGCODE)=b.ORGCODE where SENDCARDTIME >= :beginTime and SENDCARDTIME <= :endTime";
            if (!string.IsNullOrWhiteSpace(tbxTruckNo.Text))
            {
                strSql += " and CHEHAO like '%" + tbxTruckNo.Text.Trim() + "%'";
            }
            if (!string.IsNullOrWhiteSpace(tbxCardNo.Text))
            {
                strSql += " and CARDID like '%" + tbxCardNo.Text.Trim() + "%'";
            }
            if (cbbAddr.Text == "黄岛")
            {
                strSql += " and QG_BS = '3'";
            }
            else if (cbbAddr.Text == "董家口")
            {
                strSql += " and QG_BS = '4'";
            }
            if (cmbOrg.SelectedValue != null)
            {
                strSql += " and decode(a.ORGCODE,'1','01',a.ORGCODE)='" + cmbOrg.SelectedValue.ToString() + "'";
            }
            strSql += " order by CARDSTATE, SENDCARDTIME desc";
            this.cdgvRFID.DataSource = DataAccess.ExecuteDataTable(strSql, new OracleParameter(":beginTime", dtpBegin.Value), new OracleParameter(":endTime", dtpEnd.Value));
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnQuery_Click(object sender, EventArgs e)
        {
            //if (string.IsNullOrWhiteSpace(tbxCardNo.Text) && string.IsNullOrWhiteSpace(tbxTruckNo.Text))
            //{
            //    MessageBox.Show("卡号、车牌号不能同时为空！");
            //    return;
            //}
            ReLoad();
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnModify_Click(object sender, EventArgs e)
        {
            if (cdgvRFID.SelectedCells != null && cdgvRFID.SelectedCells.Count > 0)
            {
                DataGridViewRow row = cdgvRFID.SelectedCells[0].OwningRow;
                if (row.Cells["ORGCODE"].Value.ToString() != Session.CurrentOrgCode)
                {
                    MessageBox.Show("只能修改在当前库区发卡的数据！");
                    return;
                }
                if (row.Cells["CARDSTATE"].Value.ToString() != "0")
                {
                    MessageBox.Show("该卡已作废，不能修改！");
                    return;
                }
                using (FKModifyForm form = new FKModifyForm(row.Cells["CHEHAO"].Value.ToString(), row.Cells["CARDID"].Value.ToString(),
                    row.Cells["HD_WEIGHT"].Value.ToString(), row.Cells["SENDCARDTIME"].Value.ToString()))
                {
                    if (form.ShowDialog() == DialogResult.OK)
                    {
                        MessageBox.Show("修改成功！");
                        ReLoad();
                    }
                }
            }
        }

        /// <summary>
        /// 作废
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOK_Click(object sender, EventArgs e)
        {
            if (cdgvRFID.SelectedCells != null && cdgvRFID.SelectedCells.Count > 0)
            {
                DataGridViewRow row = cdgvRFID.SelectedCells[0].OwningRow;
                //if (row.Cells["ORGCODE"].Value.ToString() != Session.CurrentOrgCode)
                //{
                //    MessageBox.Show("只能作废在当前库区发卡的数据！");
                //    return;
                //}
                if (row.Cells["CARDSTATE"].Value.ToString() != "0")
                {
                    MessageBox.Show("该卡已作废！");
                    return;
                }
                DataAccess.ExecuteNonQuery("update RFID_READ set CARDSTATE='1' where CARDSTATE='0' and CARDID='" +
                    row.Cells["CARDID"].Value.ToString() + "' and SENDCARDTIME=to_date('" + row.Cells["SENDCARDTIME"].Value.ToString() + "','yyyy-mm-dd hh24:mi:ss')");
                MessageBox.Show("作废成功！");
                //DataAccess.ExecuteNonQuery("update RFID_READ set CARDSTATE='1' where decode(ORGCODE,'1','01',ORGCODE) = '" + Session.CurrentOrgCode + "' and CARDSTATE='0' and CARDID='" +
                //    row.Cells["CARDID"].Value.ToString() + "' and SENDCARDTIME=to_date('" + row.Cells["SENDCARDTIME"].Value.ToString() + "','yyyy-mm-dd hh24:mi:ss')");
                //MessageBox.Show("作废成功！");
                ReLoad();
            }
        }

        /// <summary>
        /// 取消作废
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (cdgvRFID.SelectedCells != null && cdgvRFID.SelectedCells.Count > 0)
            {
                DataGridViewRow row = cdgvRFID.SelectedCells[0].OwningRow;
                if (row.Cells["ORGCODE"].Value.ToString() != Session.CurrentOrgCode)
                {
                    MessageBox.Show("只能取消作废在当前库区发卡的数据！");
                    return;
                }
                if (row.Cells["CARDSTATE"].Value.ToString() != "1")
                {
                    MessageBox.Show("该卡未作废！");
                    return;
                }
                string strTruckNo = row.Cells["CHEHAO"].Value.ToString();
                DataTable dtRFID = DataAccess.ExecuteDataTable("select CARDID from RFID_READ where CARDSTATE = '0' and CHEHAO = '" + strTruckNo + "'");
                if (dtRFID != null && dtRFID.Rows.Count > 0)
                {
                    MessageBox.Show("取消作废失败，该车已经发卡，卡号：" + dtRFID.Rows[0]["CARDID"].ToString());
                }
                else
                {
                    string strCardNo = row.Cells["CARDID"].Value.ToString();
                    dtRFID = DataAccess.ExecuteDataTable("select CHEHAO from RFID_READ where CARDSTATE = '0' and CARDID = '" + strCardNo + "'");
                    if (dtRFID != null && dtRFID.Rows.Count > 0)
                    {
                        MessageBox.Show("取消作废失败，该卡已经与车辆【" + dtRFID.Rows[0]["CHEHAO"].ToString() + "】关联！");
                    }
                    else
                    {
                        DataAccess.ExecuteNonQuery("update RFID_READ set CARDSTATE='0' where decode(ORGCODE,'1','01',ORGCODE) = '" + Session.CurrentOrgCode + "' and CARDSTATE='1' and CARDID='" +
                            row.Cells["CARDID"].Value.ToString() + "' and SENDCARDTIME=to_date('" + row.Cells["SENDCARDTIME"].Value.ToString() + "','yyyy-mm-dd hh24:mi:ss')");
                        MessageBox.Show("取消作废成功！");
                        ReLoad();
                    }
                }
            }
        }

        private void InitQueryFilter()
        {
            dtpEnd.Value = DateTime.Now;
            dtpBegin.Value = DateTime.Now.AddMonths(-1);
            //设置库区
            string strSQL = "select ORGCODE, ORGNAME from T_SYS_ORG order by ORGCODE";
            DataTable dt = DataAccess.ExecuteDataTable(strSQL);
            if (dt != null && dt.Rows.Count > 0)
            {
                cmbOrg.DataSource = dt;
                cmbOrg.ValueMember = "ORGCODE";
                cmbOrg.DisplayMember = "ORGNAME";
                cmbOrg.SelectedValue = "";
            }
        }

        #region 读卡

        RFIDReader reader = null;

        protected override void OnInit()
        {
            base.OnInit();
            InitQueryFilter();//初始化查询条件
            //BeginRead();//连接读卡设备开始读卡
        }

        protected override void OnModuleDestroyed()
        {
            base.OnModuleDestroyed();
            if (reader != null)
            {
                reader.AfterReadCardInfo -= new RFIDReader.AfterReadCardInfoHandler(reader_AfterReadCardInfo);
                reader.CheckHandler();//检查是否还有其他对象读卡
            }
        }

        private void BeginRead()
        {
            if (reader == null)
            {
                reader = RFIDReader.GetInstance();
                reader.AfterReadCardInfo += new RFIDReader.AfterReadCardInfoHandler(reader_AfterReadCardInfo);
            }
            reader.BeginRead();
        }

        private void reader_AfterReadCardInfo(string strTid, string strEPC)
        {
            if (IsActive && !string.IsNullOrEmpty(strTid) && strTid != tbxCardNo.Text)
            {
                tbxCardNo.Text = strTid;
            }
        }

        #endregion
    }
}
